package com.mcjtf.prefix.update;

import com.google.common.base.Charsets;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mcjtf.prefix.PrefixManager;
import com.mcjtf.prefix.service.ConfigService;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Level;

public class UpdateChecker implements Listener {
    private final PrefixManager plugin;
    private final String pluginVersion;
    private String remoteVersion;
    private VersionResponse response;
    private boolean updateAvailable = false;

    public UpdateChecker(PrefixManager i) {
        plugin = i;
        pluginVersion = i.getDescription().getVersion();
        i.getServer().getPluginManager().registerEvents(this, i);
    }

    public boolean hasUpdateAvailable() {
        return updateAvailable;
    }

    public String getRemoteVersion() {
        return remoteVersion;
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        if (!updateAvailable) {
            return;
        }
        if (event.getPlayer().hasPermission("prefixmanger.update")) {
            String msg = plugin.msg(ConfigService.PREFIX + "&6检测到插件更新,请前往&7&lhttps://www.mcbbs.net/thread-333063-1-1.html&6下载最新版本.");
            event.getPlayer().sendMessage(msg);
        }
    }

    public void fetch() {
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            try {
                HttpsURLConnection con = (HttpsURLConnection) new URL("https://gitee.com/api/v5/repos/john180/PrefixManager/releases/latest").openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("User-Agent", "Mozilla/5.0");
                String json = new BufferedReader(new InputStreamReader(con.getInputStream(), Charsets.UTF_8)).readLine();
                remoteVersion = getVersion(json);
            } catch (Exception ex) {
                plugin.getLogger().info("获取新版本失败.");
                plugin.getLogger().log(Level.WARNING, "", ex);
                return;
            }
            if (remoteVersion.isEmpty()) {
                return;
            }
            updateAvailable = isOutdated();
            if (!updateAvailable) {
                return;
            }
            Bukkit.getScheduler().runTask(plugin, () -> {
                plugin.getLogger().info("--------------------------------------------");
                plugin.getLogger().info("PrefixManager新版本已发布 (" + response.getTag_name() + "),下载地址:");
                plugin.getLogger().info("http://www.mcbbs.net/thread-333063-1-1.html");
                plugin.getLogger().info("更新内容:");
                for (String line : response.getBody().split("\\r\\n")) {
                    plugin.getLogger().info(new String(line.getBytes(Charsets.UTF_8), Charset.defaultCharset()));
                }
                plugin.getLogger().info("--------------------------------------------");
            });
        });
    }

    private String getVersion(String json) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").create();
        response = gson.fromJson(json, VersionResponse.class);
        return toReadable(response.getTag_name());
    }

    private boolean isOutdated() {
        if (remoteVersion == null || remoteVersion.isEmpty()) {
            return false;
        }
        String plV = toReadable(pluginVersion);
        String spV = toReadable(remoteVersion);
        return plV.compareTo(spV) < 0;
    }

    private String toReadable(String version) {
        if (version.contains("-DEV-")) {
            version = version.split("-DEV-")[0];
        }
        return version.replace("v", "").replaceAll("\\.", "");
    }
}
